<template>
  <view>
    <view class="addressBox">
      <u-cell-group :border="false">
        <u-cell-item
          title="收货地址"
          :arrow="true"
          value="选择地址"
          :border-bottom="false"
          :border-top="false"
          :title-style="titleFont"
          :value-style="titleFont"
          :icon-style="titleFont"
          @click="choose"
        ></u-cell-item>
      </u-cell-group>
      <u-cell-group v-if="defaultAddrerss.name" :border="false" title="确认收货地址" :title-style="addressTitleStyle">
        <u-cell-item
          icon="map-fill"
          :icon-style="{color: '#F3651F'}"
          :title="`${defaultAddrerss.province} ${defaultAddrerss.city} ${defaultAddrerss.area} ${defaultAddrerss.addr}`"
          :arrow="false"
          :border-bottom="false"
          :border-top="false"
          :title-value="addressValueStyle"
        ></u-cell-item>
        <u-cell-item
          icon="account-fill"
          :icon-style="{color: '#F3651F'}"
          :title="defaultAddrerss.name"
          :title-value="addressValueStyle"
          :arrow="false"
          :border-bottom="false"
          :border-top="false"
        ></u-cell-item>
        <u-cell-item
          icon="phone-fill"
          :icon-style="{color: '#F3651F'}"
          :title="defaultAddrerss.mobile"
          :arrow="false"
          :border-top="false"
          :title-value="addressValueStyle"
        ></u-cell-item>
      </u-cell-group>
      <view v-else class="c-mt30">
        <u-empty text="还没有收货地址哦" mode="list"></u-empty>
      </view>
    </view>
    <view class="orderInforBox">
      <u-cell-group :border="false">
        <u-cell-item
          title="订单信息"
          :arrow="false"
          :border-bottom="false"
          :border-top="false"
          :title-style="titleFont"
        ></u-cell-item>

        <view class="border" v-for="(item, index) in good" :key="index">
          <orderItem :goods="item"></orderItem>
          <u-cell-item
            title="产品价格"
            :value="'￥' + floatMul(item.price, item.count)"
            :arrow="false"
            :border-bottom="false"
            :border-top="false"
            :title-style="orderInforTitle"
            :value-style="orderInforValue"
          ></u-cell-item>
          <u-cell-item
            title="产品优惠"
            :value="'-￥' + computePrice(item, 'youhui')"
            :arrow="false"
            :border-bottom="false"
            :border-top="false"
            :title-style="orderInforTitle"
            :value-style="orderInforValue"
          ></u-cell-item>
          <u-cell-item
            title="是否使用优惠券"
            @click.native="a(item.id, floatMul(item.price, item.count))"
            :arrow="true"
            :border-bottom="false"
            :border-top="false"
            :title-style="orderInforTitle"
            :value-style="orderInforValue"
          ></u-cell-item>
          <view class="orderValue">￥{{ computePrice(item, 'yue') }}</view>
        </view>

        <u-cell-item
          title="是否使用全场优惠券"
          @click.native="a('', yuanPrice)"
          :arrow="true"
          :border-bottom="false"
          :border-top="false"
          :title-style="orderInforTitle"
          :value-style="orderInforValue"
        ></u-cell-item>
        <view class="c-flex c-p15 c-flex-between">
          <view class="beizhu c-line-30">订单备注</view>
          <view>
            <u-input placeholder="请和商家协商一致" input-align="right" v-model="value" type="text" :border="false" />
          </view>
        </view>
        <u-cell-item
          class="moneyitem"
          title="总金额"
          :value="'￥' + totalPrice"
          :arrow="false"
          :border-top="false"
          :title-style="moneyStyle"
          :value-style="moneyStyle"
        ></u-cell-item>
      </u-cell-group>
      <u-button
        shape="circle"
        :hair-line="false"
        :custom-style="{
          margin: '60rpx auto',
          background: 'linear-gradient(80deg, #FFB245, #FF814A)',
          boxShadow: '0px 15px 50px 0px rgba(255, 128, 53, 0.41)',
          color: '#fff',
          border: 'none',
          height: '120rpx',
          width: '90%'
        }"
        @click="save"
        >立即支付</u-button
      >
    </view>
  </view>
</template>
<script>
  import SaveButton from '@/commponents/public/button/SaveButton'
  import orderItem from '@/commponents/public/order-item-new/index'
  import url from '../../common/util/url'
  import goods from '@/services/goods'
  import address from '@/services/address'
  import order from '@/services/order'
  import shoppingCar from '@/services/shoppingCar'
  import util from '@/common/util/index.js'
  export default {
    data() {
      return {
        params: '',
        youhuiqian: [],
        titleFont: {
          fontSize: '30rpx',
          color: '#303030',
          fontWeight: '600'
        },
        orderInforTitle: {
          color: '#8992A3',
          fontSize: '30rpx',
          fontWeight: '400'
        },
        orderInforValue: {
          color: '#393939',
          fontSize: '30rpx',
          fontWeight: '400'
        },
        moneyStyle: {
          fontSize: '38rpx',
          fontWeight: '600',
          color: '#000000'
        },
        addressTitleStyle: {
          color: '#F3651F',
          fontSize: '30rpx',
          fontWeight: '600'
        },
        addressValueStyle: {
          color: '#303030',
          fontSize: '27rpx',
          fontWeight: '400'
        },
        good: [],
        list: [],
        defaultAddrerss: {},
        newList: [],
        value: '',
        totalPrice: 0,
        yuanPrice: 0
      }
    },
    components: {
      SaveButton,
      orderItem
    },
    methods: {
      computePrice(item, type) {
        if (type == 'youhui') {
          let total
          if (item.discountType == 1) {
            let a1 = util.floatMul(item.price, item.count)
            let a2 = util.floatMul(util.floatMul(item.price, item.count), item.discountValue)
            total = util.floatSub(a1, a2)
          } else if (item.discountType == 2) {
            total = item.discountValue
          } else {
            total = 0.0
          }
          return total
        }
        if (type == 'yue') {
          if (!item.discountType) {
            return util.floatMul(item.price, item.count)
          }
          let total
          if (item.discountType == 1) {
            total = util.floatMul(util.floatMul(item.price, item.count), item.discountValue)
          } else if (item.discountType == 2) {
            total = util.floatSub(util.floatMul(item.price, item.count), item.discountValue)
          } else {
            total = 0.0
          }
          return total
        }
      },
      a(id, money) {
        wx.navigateTo({
          url: '/pages/youhuiquan/keyong?id=' + id + '&money=' + money
        })
      },
      choose() {
        uni.setStorageSync('addressFrom', url.getCurrentPageUrl())
        wx.navigateTo({
          url: '/pages/myaddress/index'
        })
      },
      getList() {
        return new Promise(resolve => {
          let zanData = uni.getStorageSync('order')
          let that = this
          that.good = []
          function Iterator(i) {
            if (i === zanData.length) {
              that.good.map(item => {
                let obj = item.skuList.find(i => {
                  if (i.id == item.skuId) return i
                })
                item.skuName = obj.name
                item.price = obj.price
                resolve()
                return null
              })
              return
            }
            goods
              .detail({
                id: zanData[i].id,
                userId: uni.getStorageSync('userId')
              })
              .then(data => {
                data.count = zanData[i].count
                data.skuId = zanData[i].skuId
                that.good.push(data)
                i++
                Iterator(i)
              })
          }
          Iterator(0)
        })
      },
      getAddress() {
        address.list().then(data => {
          this.list = data
          this.newList = this.list.map(item => {
            if (item.isDefault) {
              this.defaultAddrerss = item
              return item
            }
            return item
          })
        })
      },
      getAddressInfo() {
        address.info(this.params.addressId).then(data => {
          this.defaultAddrerss = data.data
        })
      },
      save() {
        /** 修改支付接口为微信支付 从而新增地址判断 */
        if (!this.defaultAddrerss.id) {
          wx.showToast({
            title: '还没有地址哦',
            icon: 'none',
            duration: 2000
          })
          return
        }
        if (uni.getStorageSync('orderFrom') === 'pages/shoppingCar/index') {
          shoppingCar.del(uni.getStorageSync('shoppingCarIds'))
        }
        let orderGood = uni.getStorageSync('order')
        let quan = uni.getStorageSync('quan')
        if (quan.length > 0) {
          quan.forEach(item => {
            orderGood.find((item1, index) => {
              if (item1.id == item.productId) {
                orderGood[index].userCouponId = item.userCouponId
                return item.userCouponId
              }
            })
          })
        }
        order
          .save({
            addressId: this.defaultAddrerss.id,
            userCouponId: uni.getStorageSync('quanchangquan').userCouponId,
            buyOrderDetailList: [...orderGood],
            note: this.value
          })
          .then(data => {
            uni.setStorageSync('quan', [])
            uni.setStorageSync('quanchangquan', [])
            this.pay(data.id)
          })
      },
      floatMul(a, b) {
        let c = 0
        let d = a.toString()
        let e = b.toString()
        try {
          c += d.split('.')[1].length
        } catch (f) {}
        try {
          c += e.split('.')[1].length
        } catch (f) {}
        return (Number(d.replace('.', '')) * Number(e.replace('.', ''))) / Math.pow(10, c)
      },
      /* 7.11 将人工一对一更改为线上支付 */
      pay(id) {
        order.pay(id).then(data => {
          wx.requestPayment({
            timeStamp: data.timeStamp,
            nonceStr: data.nonceStr,
            package: data.package,
            signType: data.signType,
            paySign: data.sign,
            appid: data.appId,
            success: function (res) {
              wx.switchTab({
                url: '/pages/order/my'
              })
            },
            fail: function (res) {
              console.log(res)
            },
            complete: function (res) {
              wx.redirectTo({
                url: '/pages/order/my'
              })
            }
          })
        })
      }
    },
    onShow() {
      this.yuanPrice = 0
      this.params = url.getCurrentPageParam()
      if (this.params.addressId) {
        this.getAddressInfo()
      } else {
        this.getAddress()
      }
      let quan = uni.getStorageSync('quan')
      this.getList().then(() => {
        for (let i = 0; i < quan.length; i++) {
          this.good.map((a, index) => {
            if (a.id == quan[i].productId) {
              let obj = this.good[index]
              obj.quanid = quan[i].userCouponId
              obj.discountType = quan[i].discountType
              obj.discountValue = quan[i].discountValue
              this.$set(this.good, index, obj)
            }
            return ''
          })
        }
        // let arr = []
        let sum = 0
        this.good.forEach((item, index) => {
          let cheng = util.floatMul(item.price, item.count)
          this.yuanPrice = util.floatAdd(cheng, this.yuanPrice)
          let total = 0
          if (item.discountType == 1) {
            total = util.floatMul(util.floatMul(item.price, item.count), item.discountValue)
          } else if (item.discountType == 2) {
            total = util.floatSub(util.floatMul(item.price, item.count), item.discountValue)
          } else {
            total = util.floatMul(item.price, item.count)
          }
          sum = util.floatAdd(sum, total)
        })
        // sum  有商品优惠的总价格
        // yuanPrice 无优惠的总价格
        // 全场优惠 = yuanPrice - 全场的折扣
        if (quan.length >= 1) {
          this.totalPrice = sum
        } else if (uni.getStorageSync('quanchangquan').id) {
          if (uni.getStorageSync('quanchangquan').discountType == 1) {
            this.totalPrice = util.floatMul(this.yuanPrice, uni.getStorageSync('quanchangquan').discountValue)
          }
          if (uni.getStorageSync('quanchangquan').discountType == 2) {
            this.totalPrice = util.floatSub(this.yuanPrice, uni.getStorageSync('quanchangquan').discountValue)
          }
        } else {
          this.totalPrice = this.yuanPrice
        }
      })
    }
  }
</script>
<style lang="scss" scope>
  .c-line-30 {
    line-height: 66rpx;
  }
  .mt200 {
    margin-top: 200rpx;
  }
  .border {
    border-bottom: 1px solid #e1e1e1;
    padding: 0 0 20px 0;
    position: relative;
    top: -26rpx;
  }
  .orderValue {
    color: #393939;
    text-align: right;
    font-size: 30rpx;
    font-weight: 400;
    padding-right: 32rpx;
  }
  .orderInforBox {
    padding-bottom: 60rpx;
  }
  .c-mt30 {
    margin-top: 30rpx;
  }
  .beizhu {
    color: #8992a3;
    font-size: 30rpx;
    font-weight: 400;
  }
</style>
<style scope>
  u-cell-item >>> .u-cell {
    padding: 18rpx 32rpx !important;
  }
  .moneyitem >>> .u-cell {
    padding: 40rpx 32rpx 40rpx !important;
  }
</style>
